package com.study.www.config;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

/**
 * 多数据源：数据源1
 * @author : 89007337.zhuyanpeng
 **/
@Configuration
public class Test2DataSourceConfig {

    public static final String TEST2SQLSESSIONFACTORY="test2SqlSessionFactory";


    /**
     * 数据源
     */
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.test2")
    public DataSource test2DataSource(){
        return DruidDataSourceBuilder.create().build();
    }

    /**
    *  SqlSession 工厂
    */
    @Bean(TEST2SQLSESSIONFACTORY)
    public SqlSessionFactory test2SqlSessionFactory(@Value("${mybatis.test2.mapperLocations}")  String test2MapperLocations,
                                                    @Value("${mybatis.test2.type-aliases-package}")  String test2TypeAliasesPackage,
                                                    @Qualifier("test2DataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        sqlSessionFactoryBean.setMapperLocations(
                new PathMatchingResourcePatternResolver().getResources(test2MapperLocations)
        );
        //mybatis Config 配置
        ClassPathResource classPathResource = new ClassPathResource("mybatis-config.xml");
        sqlSessionFactoryBean.setConfigLocation(classPathResource);
        sqlSessionFactoryBean.setTypeAliasesPackage(test2TypeAliasesPackage);
        return sqlSessionFactoryBean.getObject();
    }

}
